package com.hxzy.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/*
 * 全局异常处理器
 * */
@ControllerAdvice(annotations = {RestController.class})   //异常处理器---指明拦截哪些controller
@ResponseBody           //将响应数据转为json
@Slf4j                  //日志
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            //split() 拆分字符串
            String[] split = ex.getMessage().split(" ");
            String msg = "用户名 " + split[2] + " 已被注册过";
            return R.error(msg);
        }
        return R.error("出现未知错误");
    }
}
